<template>
  <div class="app-container">
    <!-- 高级查询 -->
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
    <el-row :gutter="40" class="form-item-group">
     <el-col :span="38">
       <el-form-item label="商城:">
         <el-select v-model="queryParams.mallName" placeholder="请选择商城编号" clearable size="mini">
           <el-option v-for="option in options.mallOptions" :key="option.customerName" :label="option.customerName" :value="option.customerName" />
         </el-select>
       </el-form-item>
     <!-- <el-form-item label="店铺:">
        <el-select v-model="queryParams.storeId" placeholder="请选择店铺编号" clearable size="mini" @change="loadSpuOptions()">
          <el-option v-for="option in options.storeOptions" :key="option.id" :label="option.storeName" :value="option.id" />
        </el-select>
      </el-form-item> -->
       <!-- <el-form-item label="SPU:">
        <el-select v-model="queryParams.custSpuId" placeholder="请选择店铺货号" clearable size="mini">
          <el-option v-for="option in options.spuOptions" :key="option.custGoodsId" :label="option.spuName" :value="option.custGoodsId" />
        </el-select>
         </el-form-item>
        <el-form-item label="SKU:">
            <el-input v-model="queryParams.custSkuId" size="mini" placeholder="请输入SKU" clearable @keyup.enter.native="handleQuery" />
          </el-form-item> -->

      <el-form-item label="SPU:">
          <el-input v-model="queryParams.custSpuId" size="mini" placeholder="请输入SPU" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
      <el-form-item label="SKU:">
          <el-input v-model="queryParams.custSkuId" size="mini" placeholder="请输入SKU" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="自" prop="jobDateFr">
            <el-date-picker v-model="queryParams.jobDateFr" type="date" value-format="yyyy-MM-dd" size="mini" style="width: 200px" placeholder="选择时间始" clearable />
        </el-form-item>
        <el-form-item label="至" prop="jobDateTo">
          <el-date-picker v-model="queryParams.jobDateTo" type="date" value-format="yyyy-MM-dd" size="mini" style="width: 200px" placeholder="选择时间至" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-tabs v-model="activeName">
      <el-tab-pane label="列表" name="list">
        <el-table v-loading="loading" :data="page.records" height="550" highlight-current-row @selection-change="handleSelectionChange" @sort-change="handleSortChange">
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column label="序号" type="index" />
          <el-table-column label="商品"  width="305" show-overflow-tooltip align="center" prop="cargoObjectName" />
          <!-- <el-table-column label="商城SPU" width="100" align="center"  prop="custSpuId" />
          <el-table-column label="商城SKU"   width="105" align="center" prop="custSkuId" />
          --><el-table-column label="销售日期" width="155" align="right" prop="monthYearDate" />
          <el-table-column label="销售数(件)" width="105" align="right" prop="sumQty" />
          <!-- <el-table-column label="买入价" align="right" width="105"  prop="sumAmount">
            <template slot-scope="scope">
              <span>{{ Number(scope.row.sumAmount).toFixed(2) }}</span>
            </template>
          </el-table-column> -->
          <el-table-column label="卖出价" align="right" width="105"  prop="sumAmtAr">
            <template slot-scope="scope">
              <span>{{ Number(scope.row.sumAmtAr).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <!--
                <el-table-column label="商城"  align="center" prop="mallName" / -->>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="图表" name="char">
        <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
          <single-line-chart width="800px" :chart-data="chartData" />
        </el-row>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import SingleLineChart from '@/components/Charts/SingleLineChart'
import AccountingApApi from '@/api/accounting/AccountingApApi'
import CustomerApi from '@/api/basic/CustomerApi'
import SalesOrderItemApi from '@/api/order/SalesOrderItemApi'

const defaultAccountingApFormData = {
  invoiceNo: null,
  slipNo: null,
  storeId: null,
  mallId: null,
  status: '0',
  fixStatus: '0',
  basicNo: null,
  orderSeqNo: null,
  orderItemNo: null,
  acItemId: null,
  site: null,
  bizKind: null,
  bizUnit: null,
  accUnit: null,
  branchUnit: null,
  payCust: null,
  billToCust: null,
  ptnrYn: null,
  slipDt: null,
  invoiceType: null,
  taxType: null,
  amtCur: null,
  jobDate: null,
  exrate: null,
  curr: null,
  rate: null,
  wtCnt: null,
  frtCd: null,
  frtNm: null,
  invoiceDt: null,
  miles: null,
  invSettleId: null,
  settlementId: null,
  billNo: null,
  carrierNo: null,
  dispatchId: null,
  distributionNo: null,
  inputType: null,
  autoYn: null,
  pcTerm: null,
  cargoObjectNo: null,
  cargoObjectName: null,
  vehicleNo: null,
  apTypeFlag: null,
  carrierEdiYn: null,
  amount: null,
  paiedFee: null,
  consigneeName: null,
  amtAr: null,
  cargoDamageYn: null,
  remainedAmount: null,
  originalCustName: null,
  batchWorkorderNo: null,
  shippedQtyUnit: null,
  shipperName: null,
  contractAmount: null,
  contractRate: null,
  driverNo: null,
  paymentType: null,
  settlementApplicant: null,
  returnTime: null,
  sourceItemId: null,
  askedTransitFee: null,
  settleBasedOn: null,
  settleBasedOnUnit: null,
  dispatchDate: null
}
export default {
  name: 'AccountingApList',
  components: {
    SingleLineChart
  },
  data() {
    return {
      activeName: 'list',
      options: {
        mallOptions: [],
        sysYnTypeOptions: this.$constant.sysYnTypeOptions
      },
      queryParams: {
        storeId: null,
        mallName: null,
        custSpuId: null,
        custSkuId: null,
        jobDateFr: null,
        jobDateTo: null,
        isValid: this.$constant.Y,
        sortProperty: null,
        sortDirection: null
      },
      page: {
        current: 1,
        pageSize: 1000,
        total: 0,
        records: []
      },
      chartData: {},
      returnDialog: {
        title: '退单',
        visible: false
      },
      returnDialogData: {
        returnQty: null,
        id: null
      },
      accountingApFormDialog: {
        title: '',
        visible: false
      },
      accountingApFormData: Object.assign({}, defaultAccountingApFormData),
      accountingApFormRules: {
        invoiceNo: [{ required: true, message: '发票号不能为空', trigger: 'blur' }],
        slipNo: [{ required: true, message: '支付流水号不能为空', trigger: 'blur' }]
      },
      loading: false,
      searchVisible: true,
      multipleSelection: [],
      isSingle: true,
      isMultiple: true
    }
  },
  created() {
     this.initParam()
   // this.handleQuery()
    this.loadOptions()
  },

  methods: {
    initParam() {
       this.queryParams.jobDateFr = this.getBeforeDay(60)
       this.queryParams.jobDateTo = this.parseTime(new Date(), '{y}-{m}-{d}')
       this.queryParams.mallName = '南航会员商城'
       console.log(this.queryParams)
     },
    loadOptions() {
      let that = this
      CustomerApi.list().then(response => {
        that.options.mallOptions = response.data
      })
    /*  StoreApi.list().then(response => {
        that.options.storeOptions = response.data
      })
      if (this.queryParams.storeId != null){
        CustGoodsMapApi.list(this.queryParams).then(response => {
          that.options.spuOptions = response.data
        })
      } */

    },
    /* loadSpuOptions() {
      let  that = this
      if (this.queryParams.storeId != null){
        CustGoodsMapApi.list(this.queryParams).then(response => {
          that.options.spuOptions = response.data
        })
      }

    }, */
    handleAdd() {
      this.openAccountingApFormDialog()
    },
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return AccountingApApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.openAccountingApFormDialog(id)
    },
    handleQuery() {
      this.loading = true
      AccountingApApi.skuReport(this.queryParams, this.page).then(response => {
        this.page.records = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
      AccountingApApi.skuChartReport(this.queryParams, this.page).then(response => {
        this.chartData = response.data
      })
    },
    handleView(row) {
      this.$router.push({ path: '/store/form/' + row.storeId })
    },
    // handleOrderView(row) {
    //   this.$router.push({ path: '/order/salesOrder/form/' + row.storeId })
    // },

    handleExport() {
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return AccountingApApi.exportData(this.queryParams)
      }).then(response => {
        this.$common.download(response.data)
      })
    },
    openAccountingApFormDialog(id) {
      this.accountingApFormDialog.visible = true
      if (id) {
        this.accountingApFormDialog.title = '财务应付-修改'
        AccountingApApi.get(id).then(response => {
          this.accountingApFormData = {
            ...this.accountingApFormData,
            ...response.data
          }
        })
      } else {
        this.accountingApFormDialog.title = '财务应付-添加'
      }
    },
    handleSortChange(sort) {
      if (sort.order) {
        this.queryParams.sortProperty = sort.prop
        this.queryParams.sortDirection = sort.order === 'ascending' ? 'asc' : 'desc'
      } else {
        this.queryParams.sortProperty = null
        this.queryParams.sortDirection = null
      }
      this.handleQuery()
    },
    confirmAccountingApFormDialog() {
      this.$refs['accountingApForm'].validate(valid => {
        if (valid) {
          if (this.accountingApFormData.id) {
            AccountingApApi.edit(this.accountingApFormData).then(response => {
              this.$message.success('修改成功')
              this.resetAccountingApFormDialog()
              this.handleQuery()
            })
          } else {
            AccountingApApi.add(this.accountingApFormData).then(response => {
              this.$message.success('添加成功')
              this.resetAccountingApFormDialog()
              this.handleQuery()
            })
          }
        }
      })
    },
    resetAccountingApFormDialog() {
      this.accountingApFormDialog = {
        title: '',
        visible: false
      }
      this.accountingApFormData = Object.assign({}, defaultAccountingApFormData)
      this.resetForm('accountingApForm')
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },

    handleFix(row) {

      AccountingApApi.fixData().then(() => {
        this.$message.success('修复成功!')
        this.handleQuery()
      }).catch(error => {
        console.log(error)

      })
    },

    handleReturn(row) {
         this.returnDialog.visible = true
         this.returnDialogData.returnQty = row.wtCnt
         this.returnDialogData.id = row.sourceItemId
    },
     closeReturnDialog() {
       this.returnDialog = {
         title: '退单',
         visible: false
       }
       this.returnDialogData = {
         returnQty: null
       }
        this.handleQuery()
     },
     confirmReturnDialog() {
         const params = {
           returnQty: this.returnDialogData.returnQty,
           id: this.returnDialogData.id
        }
         SalesOrderItemApi.createReturn(params).then(() => {
           this.$message.success('退单成功!')
           this.closeReturnDialog()
         })
         this.handleQuery()
     },
     handleReturnBtnShow: function(status) {
       const validStatusList = ['CREATED']
       const index = validStatusList.indexOf(status)
       if (index === -1) {
         return false
       } else {
         return true
       }
     },
    resetQuery() {
      this.page.current = 1
     this.queryParams = {
      mallId: null,
      payCust: null,
      storeId: null,
      basicNo: null,
      isValid: this.$constant.Y
    }
      this.handleQuery()
    }
  }
}
</script>
